#include "HAL.h"
#include "OSAL_debug.h"
#include "OSAL.h"
#include "OSAL_MSG.h"
#include "OSAL.h"
#include "stdlib.h"
#include "sys.h"
#include "misc.h"
#include "OSAL_MEM.h"


/*保存底层处理任务的ID*/
uint8_t HAl_TaskProcessID = 0;

/**
 * @fn HAL_Init
 * @brief 初始化底层硬件
 * @param taskID - 任务ID
 * @return none
 */
void HAL_Init(uint8_t taskID)
{
    HAl_TaskProcessID = taskID;
    delay_init();                                   //延时函数初始化
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //设置NVIC中断分组2:2位抢占优先级，2位响应优先级
    uart_init(115200);                              //串口初始化为115200
    LED_Init();                                     //初始化与LED连接的硬件接口
    BEEP_Init();                                    //初始化蜂鸣器端口
    KEY_Init();                                     //初始化与按键连接的硬件接口
    EXTIX_Init();                                   //外部中断初始化
    LED0 = 0;                                       //点亮LED0
}

/**
 * @fn HAL_ProcessEvents
 * @brief 处理底层事件
 * @param taskID - 任务ID event - 设置的事件
 * @return 事件处理后， 清除事件
 */
uint8_t HAL_ProcessEvents(uint8_t taskID, uint16_t event)
{

    uint16_t taskEvent = event;
    if(taskEvent & OSAL_MSG_EVENT)
    {
        struct osal_msg_t * msg = osal_msg_recevie();
        if(*((uint8_t *)msg->msgPtr) == 1)
        {
            osal_msg_delete(taskID);
            OSAL_TimerOneShot(HAl_TaskProcessID, LED0_INVERSE_EVT, 500);
            OSAL_SetEvent(HAl_TaskProcessID, OSAL_MSG_EVENT);
        }
     
        return (taskEvent ^ OSAL_MSG_EVENT);
    }
    if (taskEvent & LED0_INVERSE_EVT)
    {
        LED0 = !LED0;
        OSAL_TimerOneShot(HAl_TaskProcessID, LED0_INVERSE_EVT, 500);
        return (taskEvent ^ LED0_INVERSE_EVT);
    }
    else if (taskEvent & LED1_INVERSE_EVT)
    {
        LED1 = !LED1;
        return taskEvent ^ LED1_INVERSE_EVT;
    }
    else if (taskEvent & LED0_LED1_INVERSE_EVT)
    {
        LED0 = !LED0;
        LED1 = !LED1;
        return taskEvent ^ LED0_LED1_INVERSE_EVT;
    }
    else if (taskEvent & BEEP_INVERSE_EVT)
    {
        BEEP = !BEEP;
        OSAL_TimerPeriodic(HAl_TaskProcessID, BEEP_INVERSE_EVT, 500);
        //OSAL_TimerOneShot(HAl_TaskProcessID, BEEP_INVERSE_EVT, 500);
        return taskEvent ^ BEEP_INVERSE_EVT;
    }
    else
    {
        return taskEvent;
    }
}
